package com.jw.blog.interceptor;


import com.jw.blog.annotation.AccessLimit;
import com.jw.blog.utils.UserIpUtil;
import com.jw.blog.wblog.entity.custom.RequestIp;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wan Email-wlf18726994755@163.com
 * @version 1.0
 * @className AccessInterceptor
 * @date 2020/7/1 15:07
 **/
@Component
public class AccessInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            // 使用注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            // 取用户的真实IP
            String ip = UserIpUtil.getIp(request);
            // 取session中的IP对象
            RequestIp re = (RequestIp) request.getSession().getAttribute(ip);
            // 第一次请求
            if (null == re) {
                // 放入到session中
                RequestIp reIp = new RequestIp();
                reIp.setCreateTime(System.currentTimeMillis());
                reIp.setReCount(1);
                request.getSession().setAttribute(ip, reIp);
            } else {
                long createTime = re.getCreateTime();
                if (((System.currentTimeMillis() - createTime) / 1000) > accessLimit.seconds()) {
                    // 当前时间离上一次请求时间大于3秒，可以直接通过,保存这次的请求
                    RequestIp reIp = new RequestIp();
                    reIp.setCreateTime(System.currentTimeMillis());
                    reIp.setReCount(1);
                    request.getSession().setAttribute(ip, reIp);
                } else {
                    // 小于3秒，并且3秒之内请求了10次，返回提示
                    if (re.getReCount() > accessLimit.maxCount()) {
                        return false;
                    } else {
                        // 小于3秒，但请求数小于10次，给对象添加
                        re.setCreateTime(System.currentTimeMillis());
                        re.setReCount(re.getReCount() + 1);
                        request.getSession().setAttribute(ip, re);
                    }
                }
            }
        }
        return true;
    }

}
